import { Injectable } from '@nestjs/common';
import { RoleDao as Dao } from '@/servers/daos/user/role.dao';
import { RolePermissionDao } from '@/servers/daos/user/role-permission.dao';

@Injectable()
export class RoleService {

    constructor(
        private dao: Dao,
        private rolePermissionDao: RolePermissionDao
    ) { }

    /**
     * 查询所有
     */
    findAll(params: any): Promise<any> {
        return this.dao.findAll(params);
    }

        /**
    * 查看角色下的权限
    */
    async getPermission(params:any): Promise<any> {
        return this.dao.findAll(params);
    }

    /**
     * 添加
     */
    async add(params: any): Promise<any> {
        let role = await this.dao.add(params);
        for (let i = 0; i < params.keys.length; i++) {
            let item = params.keys[i];
            if (item) {
                let obj = { role_id: role.id, permission_id: item };
                
                await this.rolePermissionDao.add(obj);
            }
        }
        return role;
    }

    /**
     * 修改
     * @param params 
     */
    async update(params: any): Promise<any> {
        let del= await this.rolePermissionDao.deleteALL({ role_id: params.id });
        for (let i = 0; i < params.keys.length; i++) {
            let id = params.keys[i];
            if (id) {
                let obj = { role_id: params.id, permission_id: id };
                await this.rolePermissionDao.add(obj);
            }
        }
        return this.dao.update(params);
    }

    /**
     * 删除
     * @param params 
     */
    async delete(params: any): Promise<any> {
        return this.dao.delete(params);
    }

}
